package com.ostrich.note.ui.note.views;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.CheckBox;
import android.widget.PopupWindow;
import android.widget.SeekBar;

import com.blankj.utilcode.util.PermissionUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.ostrich.note.R;
import com.ostrich.note.base.BaseMvvmActivity;
import com.ostrich.note.databinding.ActivityNoteAddBinding;
import com.ostrich.note.entity.BaseResponseEntity;
import com.ostrich.note.event.Event;
import com.ostrich.note.room.AppDataBase;
import com.ostrich.note.room.Note;
import com.ostrich.note.room.NoteDao;
import com.ostrich.note.ui.note.adapter.NoteImageAdapter;
import com.ostrich.note.ui.note.adapter.NoteTypeAdapter;
import com.ostrich.note.ui.note.adapter.NoteTypeEditAdapter;
import com.ostrich.note.ui.note.entity.NoteEntity;
import com.ostrich.note.ui.note.entity.TypeEntity;
import com.ostrich.note.ui.note.viewmodel.NoteAddViewModel;
import com.ostrich.note.utils.DateTimeUtils;
import com.ostrich.note.utils.PermissionUtil;
import com.ostrich.note.utils.UploadUtils;
import com.wildma.pictureselector.PictureBean;
import com.wildma.pictureselector.PictureSelector;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 笔记添加
 */
public class NoteAddActivity extends BaseMvvmActivity<ActivityNoteAddBinding, NoteAddViewModel>{

    private static final int REQUEST_CODE_ALBUM = 102;

    private NoteImageAdapter mNoteImageAdapter;
    private TypeEntity data;
    private NoteTypeAdapter mNoteTypeAdapter;
    private TypeEntity.ListBean mListBean;
    private NoteDao mNoteDao;
    private long seconds;
    @Override
    protected void iniView() {
        mNoteImageAdapter = new NoteImageAdapter();
        binding.rvPicture.setAdapter(mNoteImageAdapter);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        binding.rvPicture.setLayoutManager(linearLayoutManager);

        mNoteDao = AppDataBase.getInstance().getNoteDao();

    }

    @Override
    public int getLayout() {
        return R.layout.activity_note_add;
    }

    @Override
    public void initData() {
        seconds = System.currentTimeMillis()/1000;
        String monthAndDay = DateTimeUtils.getMonthAndDay(seconds);
        binding.tvDate.setText(monthAndDay);
        String time = DateTimeUtils.getTime(seconds);
        String week = DateTimeUtils.getWeek(seconds);
        binding.tvTime.setText(time+week);

        String title = SPUtils.getInstance().getString("title");
        if(!TextUtils.isEmpty(title)){
            binding.etTitle.setText(title);
        }

        String content = SPUtils.getInstance().getString("content");
        if(!TextUtils.isEmpty(content)){
            binding.etContent.setText(content);
        }
        Set<String> images = SPUtils.getInstance().getStringSet("images");
        ArrayList<String> list = new ArrayList<>();
        for (String image : images) {
            list.add(image);
        }
        mNoteImageAdapter.setData(list);

        //分类列表数据
        viewModel.notepadClassifiedData().observe(NoteAddActivity.this, new Observer<BaseResponseEntity<TypeEntity>>() {
            @Override
            public void onChanged(BaseResponseEntity<TypeEntity> typeEntityBaseResponseEntity) {
                data = typeEntityBaseResponseEntity.getData();


            }
        });
    }

    @Override
    public void initListener() {




        binding.tvCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showPopupWindow();
            }
        });
        binding.ivFont.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                binding.clImage.setVisibility(View.INVISIBLE);
                binding.clText.setVisibility(View.VISIBLE);
            }
        });
        binding.ivPhoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                binding.clImage.setVisibility(View.VISIBLE);
                binding.clText.setVisibility(View.INVISIBLE);
            }
        });
        //拖拽字体
        binding.seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                binding.etContent.setTextSize(progress+10);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
        //打开相机
        binding.clCamera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                PictureSelector.create(NoteAddActivity.this,REQUEST_CODE_ALBUM).selectPicture();
            }
        });

        mNoteImageAdapter.setItemChildClickListener(new NoteTypeEditAdapter.ItemChildClickListener() {
            @Override
            public void onItemChildClick(View view, int position) {
                mNoteImageAdapter.deleteData(position);
                if(position>=0 && position <= thumbList.size()-1){
                    thumbList.remove(position);
                }

            }
        });

        binding.clAll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showPopupWindow(v);
            }
        });


        binding.tvOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//
//                if(mNoteImageAdapter.getList().size() != thumbList.size()){
//                    ToastUtils.showShort("图片上传中，请稍后。。。");
//                    return;
//                }



                String content = binding.etContent.getText().toString();
                String title = binding.etTitle.getText().toString();
                StringBuilder thumb = new StringBuilder();

                for (int i = 0; i < thumbList.size(); i++) {
                    if(i == thumbList.size()-1){
                        thumb.append(thumbList.get(i));
                    }else{
                        thumb.append(thumbList.get(i)+",");
                    }
                }
                if(mListBean == null){
                    ToastUtils.showShort("请选择分类");
                    return;
                }


                viewModel.notepadDetailInsert(thumb.toString(),title,System.currentTimeMillis()/1000,content,0,mListBean.getNotepad_id())
                        .observe(NoteAddActivity.this, new Observer<BaseResponseEntity>() {
                            @Override
                            public void onChanged(BaseResponseEntity baseResponseEntity) {
                                if(baseResponseEntity.getCode() == 200){
                                    ToastUtils.showShort("添加成功");

                                    finish();
                                    Event event = new Event();
                                    event.type = Event.NOTE_ADD;
                                    event.target = "NoteFragment";
                                    EventBus.getDefault().post(event);
                                }
                            }
                        });

            }
        });


    }

    private void showPopupWindow(View v) {
        //数据预加载成功后才弹出窗体，不然报错
        if(data == null){
            return;
        }
        PopupWindow popupWindow = new PopupWindow(this);
        popupWindow.setBackgroundDrawable(null);
        View view = LayoutInflater.from(this).inflate(R.layout.pop_note_type, null);
        RecyclerView recyclerView = view.findViewById(R.id.rv);
        mNoteTypeAdapter = new NoteTypeAdapter();
        recyclerView.setAdapter(mNoteTypeAdapter);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        mNoteTypeAdapter.setData(data.getList());
        //选中的分类
        mNoteTypeAdapter.setOnItemClickListener(new NoteTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                CheckBox checkBox = (CheckBox) view;
                if(checkBox.isChecked())
                mListBean = data.getList().get(position);
            }
        });

        view.findViewById(R.id.tv_edit).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Bundle bundle = new Bundle();
                bundle.putSerializable("data",data);
                startActivityBundle(TypeEditActivity.class,bundle);


            }
        });
        popupWindow.setContentView(view);
        popupWindow.setWidth(400);//不规范 px->dp
        popupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        popupWindow.setOutsideTouchable(true);
        popupWindow.showAsDropDown(v,-170,0, Gravity.BOTTOM|Gravity.CENTER);//不规范

        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {

            }
        });
    }

    private List<String> thumbList = new ArrayList<>();
    //打开相机或相册后返回结果
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == REQUEST_CODE_ALBUM && resultCode == Activity.RESULT_OK){
            if (data != null) {
                PictureBean pictureBean = data.getParcelableExtra(PictureSelector.PICTURE_RESULT);
                String path = pictureBean.getPath();
                mNoteImageAdapter.setData(path);

                String upload = UploadUtils.upload(path);
                thumbList.add(upload);
            }
        }
    }

    private void showPopupWindow() {
        PopupWindow popupWindow = new PopupWindow(this);
        View view = LayoutInflater.from(this).inflate(R.layout.pop_note_add, null);

        view.findViewById(R.id.tv_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });
        //保存
        view.findViewById(R.id.tv_save).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String date = binding.tvDate.getText().toString();
                String time = binding.tvTime.getText().toString();
                String title = binding.etTitle.getText().toString();
                String content = binding.etContent.getText().toString();
                List<String> list = mNoteImageAdapter.getList();
                Set<String> set = new HashSet();
                for (String s : list) {
                    set.add(s);
                }
                SPUtils.getInstance().put("title",title);
                SPUtils.getInstance().put("content",content);
                SPUtils.getInstance().put("images",set);

                ToastUtils.showShort("保存成功");

                {

//                    if(mNoteImageAdapter.getList().size() != thumbList.size()){
//                        ToastUtils.showShort("图片上传中，请稍后。。。");
//                        return;
//                    }



                    String content_ = binding.etContent.getText().toString();
                    String title_ = binding.etTitle.getText().toString();
                    StringBuilder thumb = new StringBuilder();

                    for (int i = 0; i < thumbList.size(); i++) {
                        if(i == thumbList.size()-1){
                            thumb.append(thumbList.get(i));
                        }else{
                            thumb.append(thumbList.get(i)+",");
                        }
                    }
                    if(mListBean == null){
                        ToastUtils.showShort("请选择分类");
                        return;
                    }


                    viewModel.notepadDetailInsert(thumb.toString(),title_,System.currentTimeMillis()/1000,content_,0,mListBean.getNotepad_id())
                            .observe(NoteAddActivity.this, new Observer<BaseResponseEntity>() {
                                @Override
                                public void onChanged(BaseResponseEntity baseResponseEntity) {
                                    if(baseResponseEntity.getCode() == 200){
                                        ToastUtils.showShort("添加成功");

                                        finish();
                                        Event event = new Event();
                                        event.type = Event.NOTE_ADD;
                                        event.target = "NoteFragment";
//                                        event.data =
                                        EventBus.getDefault().post(event);
                                        popupWindow.dismiss();
                                    }
                                }
                            });

                }




            }
        });
        //草稿箱
        view.findViewById(R.id.tv_draft).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String date = binding.tvDate.getText().toString();
                String time = binding.tvTime.getText().toString();
                String title = binding.etTitle.getText().toString();
                String content = binding.etContent.getText().toString();
                List<String> list = mNoteImageAdapter.getList();
                StringBuilder thumb = new StringBuilder();

                for (int i = 0; i < list.size(); i++) {
                    if(i == list.size()-1){
                        thumb.append(list.get(i));
                    }else{
                        thumb.append(list.get(i)+",");
                    }
                }


                Note note = new Note(0, date, time, title, content, thumb.toString());
                note.setYearMonth(DateTimeUtils.getMonthAndDay(seconds));
                note.setDayWeek(DateTimeUtils.getDay(seconds)+DateTimeUtils.getWeek(seconds));

                mNoteDao.insert(note);
                ToastUtils.showShort("存入草稿箱成功");
                popupWindow.dismiss();
            }
        });
        //放弃保存
        view.findViewById(R.id.tv_giveup).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                binding.etContent.setText("");
                binding.etTitle.setText("");
                popupWindow.dismiss();

            }
        });
        view.findViewById(R.id.tv_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
                finish();
            }
        });

        popupWindow.setBackgroundDrawable(null);
        popupWindow.setContentView(view);//设置布局
        backgroundAlpha(0.5F);//背景半透明
        popupWindow.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        popupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        popupWindow.setOutsideTouchable(true);//点击外部取消
        popupWindow.showAtLocation(binding.getRoot(), Gravity.BOTTOM,0,0);
        //窗体消失监听:恢复全透明效果
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                backgroundAlpha(1.0f);
            }
        });

    }

    public void backgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = bgAlpha; //0.0-1.0
        getWindow().setAttributes(lp);
    }



    @Override
    public void createViewModel() {
        viewModel = new ViewModelProvider(this).get(NoteAddViewModel.class);
    }






}